package com.hllxd.hism.passport.login.gateway.controller;

import com.hllxd.hism.passport.login.gateway.exception.BusinessException;
import com.hllxd.hism.passport.login.gateway.model.DynamicCodeResponse;
import com.hllxd.hism.passport.login.gateway.model.LogOnDynamicCodeResponse;
import com.hllxd.hism.passport.login.gateway.service.PassportService;
import com.hllxd.hism.passport.login.gateway.util.CookieUtil;
import com.hllxd.hism.passport.login.gateway.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  Personal Mobile系统端登录对应的操作
 *  @author lixiyong01
 *  @date 2021.07.13
 */
@Slf4j
@RestController
@RequestMapping("/cdata/passport/v1/pm_login")
public class PmLoginController {

    private final static Logger LOGGER = LoggerFactory.getLogger(PmLoginController.class);

    @Autowired
    private PassportService passportService;

    /**
     * 移动端登录：发送短信动态码
     */
    @ResponseBody
    @RequestMapping(value = "/sendDynamicCodeMobile", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Object sendDynamicCode(
        @RequestParam(value = "phoneNumber", required = true) String phoneNumber,
        @RequestParam(value = "plat", required = false, defaultValue = "0") int plat ) throws IOException {
        log.info("params: {},{}.",phoneNumber, plat);
        DynamicCodeResponse response;
        try {
            response = passportService.sendDynamicCode(phoneNumber, plat);
        } catch (BusinessException e) {
            return ResultUtils.errorResult(e.code, e.msg);
        }
        return ResultUtils.result(response);
    }

    /**
     * 登录
     * @param phoneNumber 手机号码
     * @param dynamicCode 动态码
     * @param plat  默认是0-web登录 1-移动 3-小程序
     * @param request 请求
     * @param response 响应
     * @return JSON
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/logOnDynamicCodeMobile", method = RequestMethod.POST, produces ="application/json;charset=UTF-8")
    public Object logOn(
        @RequestParam(value = "phoneNumber", required = true) String phoneNumber,
        @RequestParam(value = "dynamicCode", required = true) String dynamicCode,
        @RequestParam(value = "plat", required = false, defaultValue = "0") int plat,
        HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        log.info("params: {},{},{}",phoneNumber,dynamicCode, plat);
        LogOnDynamicCodeResponse logOnResult;
        try {
            logOnResult = passportService.logOnDynamicCode(phoneNumber, dynamicCode, plat);
        } catch (BusinessException e) {
            return ResultUtils.errorResult(e.code, e.msg);
        }
        return ResultUtils.result(logOnResult);
    }


    /**
     *  SSO登录
     * @param username
     * @return JSON
     * @throws IOException
     */

    @ResponseBody
    @RequestMapping(value = "/logOnMobileSSO", produces = "application/json;charset=UTF-8")
    public Object logOnMobileSSO(
                           @RequestParam(value = "username", required = true) String username,
                           @RequestParam(value = "encode", required = true) String encode,
                           @RequestParam(value = "plat", required = false, defaultValue = "0") int plat,
                           HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("params: {},{},{}",username,encode, plat);
        LogOnDynamicCodeResponse logOnResult;
        try {
            String oaName = CookieUtil.getCookieValue(request, "58oaname");
            String ssoCookie = CookieUtil.getCookieValue(request, "ssoCookie");
            String dunCookie = CookieUtil.getCookieValue(request, "dunCookie");
            if(oaName==null || ssoCookie==null) {
                log.warn("cookie is invalid. username: {}, {}, sso: {}, {}.", username, oaName, encode, ssoCookie);
                throw new BusinessException("00000002","cookie无效");
            }
            String encode2 = ssoCookie.substring(0,8);
            log.info("oaName: {}, ssoCookie: {}, dunCookie: {}", oaName, ssoCookie, dunCookie);
            if(!oaName.equals(username) || !encode.equals(encode2) ) {
                log.warn("username: {}, {}, sso: {}, {}", username, oaName, encode, encode2);
               throw new BusinessException("00000002","user验证失败");
            }
            logOnResult = passportService.logOnSSO(username, plat);
        } catch (BusinessException e) {
            return ResultUtils.errorResult(e.code, e.msg);
        }
        return ResultUtils.result(logOnResult);
    }

    /**
     * 登出处理
     * @param accessToken Token
     * @param request 请求
     * @param response 响应
     * @return 返回JSON
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/logoffMobile", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Object logOff(@RequestParam(value = "accessToken", required = true) String accessToken,
                       HttpServletRequest request, HttpServletResponse response) throws Exception {
        String success = passportService.logOff(accessToken);
        return ResultUtils.result(success);
    }



    // 扫码登录
    @ResponseBody
    @RequestMapping(value = "/logOnQRCode", produces = "application/json;charset=UTF-8")
    public String logOnQRCode(@RequestParam String content,
                              @RequestParam String accessToken) throws IOException {

//        LogOnQRCodeResult result = passportClient.logOnQrCode(content, accessToken);
//        if (result.isResult()) {
//            return generateSuccessResult("扫码登录成功");
//        } else {
//            if (result.getErrorCode() == null) {
//                throw new IllegalStateException("错误码异常!");
//            }
//            return PassportUtil.generateResult(result.getErrorCode());
//        }
        return null;
    }

//    @AutoPassSystemEventLog
    @RequestMapping(value ="/loginTFZ",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Object CompanyWechatLoginTFZ(@RequestParam(value = "code", required = true) String code,
                                        @RequestParam(value = "secret", required = true) String secret,
                                        HttpServletRequest request) {
        LOGGER.info("CompanyWechat login request secret " +secret+"  code "+code);
//        try {
//            JSONObject responseBody = new JSONObject();
//            responseBody.put("code", "000");
//            responseBody.put("msg", "执行成功");
//            responseBody.put("success", true);
//
//            //请求accessTokenUrl，获取accessToken
//            String accessTokenUrl = String.format(urlProperties.getAccessTokenUrl(), properties.getCropid(), secret);
//            HttpRespons accessTokenRes = HttpRequester.sendGet(accessTokenUrl);
//            if (StringUtils.isEmpty(accessTokenRes.getContent())) {
//                return generateFailureReuslt(PassportErrorCode.COMPANY_WECHAT_ACCESSTOKEN_FAILED, null);
//
//            }
//            JSONObject jsonObject = JSONObject.parseObject(accessTokenRes.getContent());
//            if (!jsonObject.getString("errcode").equals(SUCCESS_CODE)) {
//                LOGGER.error("CompanyWechatLoginTFZ accessTokenRes error : "+jsonObject.getString("errcode"));
//                return generateFailureReuslt(PassportErrorCode.COMPANY_WECHAT_LOGON_FAILED, null);
//            }
//            String accessToken = jsonObject.getString("access_token");
//
//            //请求sessionUrl，获取session，拿到userID
//            String sessionUrl = String.format(urlProperties.getSessionUrl(), accessToken, code);
//            HttpRespons sessionRes = HttpRequester.sendGet(sessionUrl);
//            if (StringUtils.isEmpty(sessionRes.getContent())) {
//                return generateFailureReuslt(PassportErrorCode.COMPANY_WECHAT_SESSION_FAILED, null);
//            }
//            JSONObject object = JSONObject.parseObject(sessionRes.getContent());
//            if (!object.getString("errcode").equals(SUCCESS_CODE)) {
//                LOGGER.error("CompanyWechatLoginTFZ sessionRes error : "+object.getString("errcode"));
//                return generateFailureReuslt(PassportErrorCode.COMPANY_WECHAT_LOGON_FAILED, null);
//            }
//            Long userID = object.getLong("userid");
//
//            UserServiceOuterClass.LogOnResult res = passportClient.logOnUserID(userID.toString(),2,request);
//
//            if (!res.getResponseHeader().getCode().equals(BasicErrorCode.SUCCESS.getCode())) {
//                return generateFailureReuslt(PassportErrorCode.COMPANY_WECHAT_LOGON_FAILED, null);
//            }
//            responseBody.put("accessToken", res.getAccessToken().getTokenValue());
//            LOGGER.info("=====>自动登录接口返回值：" + responseBody.toString() + "<=====");
//            return responseBody;
//        } catch (Exception e) {
//            LOGGER.error("CompanyWechatLoginTFZ error : ", e);
//            return generateFailureReuslt(PassportErrorCode.COMPANY_WECHAT_LOGON_FAILED, null);
//        }
        return null;
    }
}
